import Util from '../../utils/util.js';
import {getOrderDeliverList, getOrderDeliverStat} from "../../api/order";
import Status from "../../utils/status";
import {getDeliverInitData} from "../../api/member";

const app = getApp()
Page({

  data: {
    bottom: 30,
    topHeight: 60,

    current: 0,
    lists: [],
    curIndex: 0,
    checkAll: false,

    date: '',
    show: false,
    fields: [
      {title: "当前店铺", name: "shop_id", level: 1, type: "select", range_key: "title"},
      {
        title: "菜单",
        name: "menu_type",
        default_val: 0,
        type: "select",
        level: 1,
        range_key: "title",
        child: Status.menuTypes()
      },
      {title: "位置", name: "city_id", level: 3,},
      {title: "状态", name: "status", type: "select", default_val: 12, level: 1, range_key: 1}
    ],

    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    page: 1,
    et_show: true,

    printerTypeList: {
      order: "打印订单",
      label: "打印品单",
      stall: "打印档口菜品汇总单",
    },

    shopTypes: ["单店", "食堂"],
    shop_type: 0,

    tabNavs: [
      "全部",
      "汇总"
    ],

    tabIndex: 0,
    statCheckAll: false,

    filter: {},
    orderDetailDialog: false,
    currentOrder: null,
    selectIds: [],

    statusList: {
      12: "确认出餐",
      16: "确认分拣",
      17: "确认送达",
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20,
      current_date: Util.formatTime(6)
    })

    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
      })
      that.initData();
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      that.initTop();
      that.onLoadTabbar();
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this,
      is_refresh = wx.getStorageSync("is_refresh");

    //关闭打印弹窗
    if (wx.getStorageSync("is_printer_refresh")) {
      this.setData({
        printerTypeDialog: false,
        isCheckAll: false,
        selectIds: null
      })
      wx.removeStorageSync("is_printer_refresh");
    }

    if (is_refresh) {
      let filter = this.data.filter || {}

      this.setData({
        selectIds: null
      })

      if (this.data.tabIndex == 1) {
        if (!Util.isEmpty(filter['stat_city_ids'])) {
          delete filter['stat_city_ids'];
        }
        this.setData({
          filter: filter,
        })
        this.getStat();
      } else {
        if (!Util.isEmpty(filter['ids'])) {
          delete filter['ids'];
        }
        that.setData({
          loadend: false,
          loading: false,
          page: 1,
          filter: filter,
          lists: [],
        });
        that.getLists()
      }
      wx.removeStorageSync("is_refresh");
    }

  },

  changeShopType(e) {//切换店铺类型
    this.setData({
      shop_type: e.currentTarget.dataset.v || 0,
      loadend: false,
      loading: false,
      page: 1,
      total: 0,
      lists: [],
    });
    // 初始化数据
    this.initData();
  },

  initData() {//初始化数据
    const that = this;
    that.initFilter();

    wx.showLoading({
      title: "正在加载..."
    })
    getDeliverInitData({
      shop_type: that.data.shop_type || 0,
    }).then(res => {
      that.setData({...res.data});

      that.setData({
        userInfo: res.data.member || []
      })

      let fields = that.data.fields
      let filter = that.data.filter || {};
      filter['shop_type'] = that.data.shop_type || 0;
      filter['status'] = 12;


      if (fields[1].name === 'deliver_time') {
        fields[1].child = Util.SplitObject(that.data.deliver_timeList, {0: "不限"});
      }

      fields[0].child = res.data.suppliers || []

      if (that.data.shop_type == 0) { //单店-全部
        fields[0].child.unshift({title: "全部", id: -1})
        filter['shop_id'] = -1;
      }

      if (!Util.isEmpty(fields[0].child)) {
        fields[0].child[0].active = true;
        fields[0].subtitle = fields[0].child[0].title
        filter[fields[0].name] = fields[0].child[0].id;

        if (fields[0].child[0].type == 1) { //食堂需要打印汇总单
          let printerTypeList = that.data.printerTypeList
          printerTypeList['keshi'] = "打印科室汇总单";
          that.setData({
            printerTypeList: printerTypeList
          })
        }
      }

      let areaList = res.data.areaList || []
      areaList.unshift({title: "不限", id: -1, level: 1, pid: 0});
      if (!Util.isEmpty(areaList)) {
        for (const k in areaList) {
          if (Util.isEmpty(areaList[k]._child)) {
            continue;
          }

          areaList[k]._child.unshift({title: "不限", id: -1, level: 2, pid: areaList[k].id});
        }
      }

      fields[2].child = areaList || []
      let statusList = [];
      for (const k in res.data.statusList) {
        statusList.push({
          title: res.data.statusList[k],
          id: k,
          active: (k == 12 ? true : false)
        })

        if (k == 12) {
          fields[3].subtitle = res.data.statusList[k];
          filter['status'] = 12;
        }
      }

      fields[3].child = statusList;
      that.setData({
        fields: fields,
        filter: filter,
        tabIndex: 0,

        loadend: false,
        loading: false,
        page: 1,
        lists: []
      })

      that.getLists();
      that.initTop();
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.hideLoading();
    })

  },

  initFilter() { //初始化顶部-筛选菜单
    const that = this,
      type = this.data.shop_type || 0;

    let fields = this.data.fields;
    if (type == 1) { //食堂
      fields[1] = {
        title: "菜单",
        name: "menu_type",
        default_val: 0,
        type: "select",
        level: 1,
        range_key: "title",
        child: Status.menuTypes()
      };

    } else {
      fields[1] = {
        title: "送达时间",
        name: "deliver_time",
        default_val: 0,
        type: "select",
        level: 4,
        child: {}
      };
    }

    this.setData({
      fields: fields,
      shop_type: type,
      // filter: {}
    })

  },

  // 切换时间
  changeDate(e) {
    const that = this,
      type = e.currentTarget.dataset.v;

    this.setData({
      current_date: Util.preNextDate(this.data.current_date, type),
      loadend: false,
      loading: false,
      page: 1,
      total: 0,
      lists: [],
      checkAll: false,
      statList: []
    })

    if (this.data.tabIndex == 1) {
      this.getStat();
    } else {
      this.getLists();
    }
  },

  changeTab(e) {
    const that = this;
    let filter = that.data.filter || {}
    this.setData({
      tabIndex: e.currentTarget.dataset.key,
      selectIds: [],
      checkAll: false
    })

    if (this.data.tabIndex == 1) {//统计数据
      if (!Util.isEmpty(filter['ids'])) {
        delete filter['ids'];

        that.setData({
          filter: filter
        })
      }
      this.getStat();
    } else {

      if (!Util.isEmpty(filter['stat_city_ids'])) {
        delete filter['stat_city_ids'];

        that.setData({
          filter: filter
        })
      }
      that.setData({
        loadend: false,
        loading: false,
        page: 1,
        total: 0,
        lists: []
      });
      that.getLists()
    }
    this.initTop();
  },

  getStat() {//统计数据
    const that = this;
    let filter = this.data.filter
    filter['page_num'] = that.data.page;
    filter['current_date'] = this.data.current_date;
    filter['shop_type'] = this.data.shop_type || 0;

    wx.showLoading({title: "正在加载..."})
    getOrderDeliverStat(filter).then(res => {
      that.setData({...res.data})
    }).catch(errmsg => {
      Util.Tips({title: errmsg}, {tab: 3})
    }).finally(() => {
      wx.hideLoading()
    });

  },

  statCheckAll(e) {
    this.setData({
      checkAll: !this.data.checkAll
    })

    const that = this;
    let statList = this.data.statList || null;
    if (Util.isEmpty(statList)) return
    statList.forEach(e1 => {
      e1.active = that.data.checkAll
    })
    this.setData({
      statList: statList
    })
  },

  statCheck(e) {
    const that = this,
      key = e.currentTarget.dataset.key;

    let statList = this.data.statList || null;
    if (Util.isEmpty(statList)) return
    statList[key].active = !statList[key].active;
    this.setData({
      statList: statList
    })

    let selectIds = [];
    statList.forEach(e1 => {
      if (e1.active) selectIds.push(e1.city_id)
    })
    this.setData({
      selectIds: selectIds
    })
  },

  changeFilterFun(e) {
    const that = this;
    let filter = {}
    if (e.detail) {
      for (const i in e.detail) {
        filter[i] = e.detail[i]
      }
    }

    if (!Util.isEmpty(filter['ids'])) {
      delete filter['ids'];
    }

    for (const k in filter) {
      if (filter[k] && filter[k] != -1) continue
      delete filter[k]
    }

    if (!Util.isEmpty(filter['status'])) {
      this.setData({
        tabIndex: 0,
        statCheckAll: false,
      })
    }

    this.setData({
      checkAll: false,
      selectIds: [],
      filter: filter
    })

    if (this.data.tabIndex == 1) {
      this.getStat();
      return
    }

    that.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: []
    });

    if (!Util.isEmpty(filter.shop_id)) {

      let fields = this.data.fields
      fields[0].child.map((e1, idx) => {
        if (e1.id != filter.shop_id) {
          return true;
        }

        let printerTypeList = that.data.printerTypeList
        if (e1.type == 1) {
          printerTypeList['keshi'] = "打印科室汇总单";
        } else {
          if (!Util.isEmpty(printerTypeList['keshi'])) {
            delete printerTypeList['keshi'];
          }
        }

        that.setData({
          printerTypeList: printerTypeList
        })

      })
    }

    that.getLists()
    this.initTop()
    this.onLoadTabbar();
  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      wx.stopPullDownRefresh()
      return;
    }

    that.setData({loading: true, loadTitle: '加载更多内容'});
    let filter = that.data.filter || {}

    filter['page_num'] = that.data.page;
    filter['shop_type'] = this.data.shop_type || 0;
    filter['current_date'] = this.data.current_date;

    getOrderDeliverList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = app.SplitArray(list, lists);

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        total: res.data.total || 0,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        page: that.data.page + 1,
        et_show: lists.length > 0
      });

      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      app.Tips({title: errmsg})
    })
  },

  selectOrder(e) {
    const that = this,
      key = e.currentTarget.dataset.key

    let lists = this.data.lists || [],
      selectIds = [];

    lists[key].active = lists[key].active !== true;
    let ids = [];
    lists.map((e1, k1) => {
      if (e1.active == true) {
        selectIds.push(e1.id);
      }
    })

    let filter = this.data.filter || {}
    if (!Util.isEmpty(filter['ids'])) {
      delete filter["ids"];
    }
    this.setData({
      lists: lists,
      selectIds: selectIds
    })

  },

  /* checkAll(e) {  //选择所有的
     const that = this;
     let checkAll = this.data.checkAll,
       filter = this.data.filter || {};
     checkAll = checkAll !== true

     let lists = this.data.lists;
     if (checkAll) {
       lists.map((e1, k1) => {
         e1.active = true;
       })
     } else {
       lists.map((e1, k1) => {
         e1.active = false;
       })
     }

     if (!Util.isEmpty(filter['ids'])) {
       delete filter['ids'];
     }

     this.setData({
       lists: lists,
       checkAll: checkAll,
       // filter: filter
     })

   },*/

  checkAll(e) {  //选择所有的
    const that = this;
    let isCheckAll = this.data.isCheckAll
    isCheckAll = isCheckAll !== true;

    let lists = this.data.lists,
      selectIds = [];

    if (isCheckAll) {
      lists.map((e1, k1) => {
        e1.active = true;
        selectIds.push(e1.id)
      })
    } else {
      lists.map((e1, k1) => {
        e1.active = false;
      })
      this.setData({
        selectIds: []
      })
    }

    this.setData({
      lists: lists,
      // selectIds: selectIds,
      isCheckAll: isCheckAll
    })

  },

  goToPage(e) {
    // 判断是否有数据
    const statList = this.data.statList,
      lists = this.data.lists;

    let filter = this.data.filter,
      statCityIds = [],
      selectIds = this.data.selectIds || null;

    if (parseInt(filter['shop_id'] || 0) <= 0) {
      return Util.Tips({title: "请选择店铺", hideMask: true});
    }

    if (e.currentTarget.dataset.type == 1) {
      if (selectIds.indexOf(e.currentTarget.dataset.v) == -1) {
        selectIds.push(e.currentTarget.dataset.v)
      }
    }

    if (!this.data.isCheckAll && (Util.isEmpty(selectIds) || selectIds.length == 0)) {  //全选
      return Util.Tips({title: "请至少选择一项", hideMask: true});
    }

    if (!this.data.isCheckAll) {
      filter[this.data.tabIndex == 1 ? 'stat_city_ids' : 'ids'] = selectIds.join("-");
    }

    wx.setStorageSync("deliver_filter", JSON.stringify(filter));
    wx.navigateTo({url: "../delivery/confirm"})
  },

  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },

  onConfirm(event) {
    const [start, end] = event.detail;

    let start_time = `${this.formatDate(start)}`,
      end_time = `${this.formatDate(end)}`

    this.setData({
      show: false,
      date: Util.formatTime(3, start_time) + '-' + Util.formatTime(3, end_time),
    });
  },

  initTop() {
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
      that.onLoadTabbar();
    }).then(() => {
      wx.createSelectorQuery().select('.navbar')
        .boundingClientRect((rect) => {
          if (!rect) {
            return;
          }
          let marginTop = rect.height
          that.setData({
            marginTop: marginTop,
            top: marginTop + 10
          })
        })
        .exec();

    })
  },

  showOrderDetail(e) {
    const that = this,
      index = e.currentTarget.dataset.index;

    that.setData({
      orderDetailDialog: true,
      currentOrder: that.data.lists[index] || null
    })

  },
  closeOrderDialog(e) {
    this.setData({
      orderDetailDialog: false,
      currentOrder: null
    })
  },

  closeLayer(e) {
    this.setData({
      printerTypeDialog: false,
      selectIds: null,
      isCheckAll: false
    })
    let lists = this.data.lists || [];
    lists.map(e1 => {
      e1.active = false;
    })
    this.setData({lists: lists})
  },

  shopPrinterDialog(e) {
    const that = this,
      type = e.currentTarget.dataset.type || 0,
      filter = this.data.filter || null;

    let selectIds = this.data.selectIds || [];
    if (type == 1) {
      selectIds = [];
      selectIds.push(e.currentTarget.dataset.v);
      this.setData({
        selectIds: selectIds,
        isCheckAll: false
      })
    }

    if (Util.isEmpty(filter.shop_id) || filter.shop_id <= 0) {
      return Util.Tips({title: "请选择店铺", hideMask: true});
    }

    if (Util.isEmpty(selectIds) && !this.data.isCheckAll) {
      return Util.Tips({title: "至少选择一项", hideMask: true});
    }

    this.onLoadTabbar();
    this.setData({
      printerTypeDialog: true,
    })
  },

  goPrinter(e) { //去打印
    const that = this,
      filter = this.data.filter || {},
      selectIds = this.data.selectIds || [];

    let params = [];
    if (Util.isEmpty(selectIds) && !this.data.isCheckAll) {
      return Util.Tips({title: "至少选择一项", hideMask: true});
    }
    params.push("printer_type=" + e.currentTarget.dataset.key);
    for (const k in filter) {
      params.push(k + "=" + filter[k])
    }

    if (selectIds.length) {
      params.push("id=" + selectIds.join("-"));
    }

    wx.navigateTo({
      url: '../printer/confirm?' + params.join('&') + "&original=delivery"
    })
  },

  copyTxt: function (event) {
    const txt = event.currentTarget.dataset.v;
    if (!txt) return;
    wx.setClipboardData({
      data: txt.toString(),
      success: function (res) {
        return app.Tips({title: "复制成功", hideMask: true})
      }
    })
  },

  onClose() {
    this.setData({show: false});
  },

  onDisplay() {
    this.setData({show: true});
  },

  makePhoneCall(e) {
    const mobile = e.currentTarget.dataset.mobile;
    Util.callPhone(mobile)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;

          let bottom = parseInt(rect.height) + 15,
            cart_bottom = parseInt(rect.height) + 15;
          if (that.data.isIphoneX) {
            bottom += 20;
            cart_bottom += 34
          }
          that.setData({
            // bottom: bottom,
            cart_bottom: cart_bottom
          })
        }).exec()
    });
  },

  onTabbar(e) {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
    });

    if (!Util.isEmpty(e)) {
      this.setData({
        bottom: e.detail
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getLists()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})